package com.xmall.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.dto.login.PermissionTreeDto;
import com.xmall.sys.define.request.permission.PermissionQueryRequest;
import com.xmall.sys.entity.Permission;
import com.xmall.sys.mapper.PermissionMapper;
import com.xmall.sys.service.IPermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    /**
     * 权限树
     */
    @Override
    public List<PermissionTreeDto> treeList(PermissionQueryRequest request) {
        return createTree(this.list());
    }

    /**
     * 生出树结构
     */
    public List<PermissionTreeDto> createTree(List<Permission> permissions){
        return permissions.stream()
            .filter(permission -> permission.getParentId() == 0)
            .map(permission -> {
                PermissionTreeDto dto = new PermissionTreeDto();
                BeanUtils.copyProperties(permission, dto);
                dto.setChildren(children(dto.getId(), permissions));
                return dto;
            })
        .sorted(Comparator.comparing(PermissionTreeDto::getSort))
        .collect(Collectors.toList());
    }

    private List<PermissionTreeDto> children(Long parentId, List<Permission> permissions){
        return permissions.stream().filter(permission -> permission.getParentId() == parentId).map(permission -> {
                PermissionTreeDto dto = new PermissionTreeDto();
                BeanUtils.copyProperties(permission, dto);
                dto.setChildren(children(dto.getId(), permissions));
                return dto;
            })
        .sorted(Comparator.comparing(PermissionTreeDto::getSort))
        .collect(Collectors.toList());
    }
}
